package com.icesoft.system.safe.filter.impl;

import com.icesoft.framework.core.util.ResponseUtils;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.system.safe.filter.HeadSafeRequestFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class ContentTypeFilter implements HeadSafeRequestFilter {

	private final static String XMLHttpRequest = "XMLHttpRequest";

	@Override
	public boolean headFilter(HttpServletRequest request, HttpServletResponse response) {
		String xRequestedWith = request.getHeader("x-requested-with");
		if (!XMLHttpRequest.equals(xRequestedWith)) {
			String errMsg = "错误的请求头x-requested-with：" + xRequestedWith + "，请设置请求头x-requested-with：" + XMLHttpRequest;
			log.info(errMsg);
			ResponseUtils.writeJson(response, JsonResult.FAIL_AUTHENTICATION(errMsg));
			return false;
		}
		if ("GET".equals(request.getMethod())) {
			return true;
		}
		String contentType = request.getContentType();
		if (StringUtils.isBlank(contentType)) {
			ResponseUtils.writeJson(response, JsonResult.FAIL_AUTHENTICATION("contentType不能为空"));
			return false;
		}
		if (contentType.toLowerCase().startsWith(MediaType.APPLICATION_FORM_URLENCODED_VALUE.toLowerCase())) {
			String errMsg = "错误的请求头contentType：" + contentType;
			log.info(errMsg);
			ResponseUtils.writeJson(response, JsonResult.FAIL_AUTHENTICATION(errMsg));
			return false;
		}
		return true;
	}
}
